package com.suning.sawp.test.bi;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

public class BiEveryMonthTruncateSql {
    private static final String statisDate = "20170501";
    
    // 会员总计提成信息
    private static final String STORE_TOT_INC_D_T = "STORE_TOT_INC_D_T";
    // 发展会员累计表
    private static final String STORE_TOT_MEMBER_D_T = "STORE_TOT_MEMBER_D_T";
    // 月累计收入清单表
    private static final String STORE_AC_INC_DETAIL_D_T = "STORE_AC_INC_DETAIL_D_T";
    
    /**
     * yyyyMMdd
     */
    private static final Pattern YYYYMMDD_PATTERN = Pattern.compile("\\d{4}\\d{2}\\d{2}");
    
    /**
     * yyyyMM
     */
    private static final Pattern YYYYMM_PATTERN = Pattern.compile("\\d{4}\\d{2}");
    
    public static void main(String[] args) {
        String index = getIndex(statisDate);
        // 删除会员总计提成信息
        createTruncateSql(STORE_TOT_INC_D_T, index, "");
        // 删除发展会员累计表
        createTruncateSql(STORE_AC_INC_DETAIL_D_T, index, "");
        // 删除月累计收入清单表
        createTruncateSql(STORE_TOT_MEMBER_D_T, index, "");
        // 删除月累计收入重抛数据备份表
        createTruncateSql(STORE_AC_INC_DETAIL_D_T, index, "_REW");
    }
    
    private static String getIndex(String statisDate) {
        String indexStr = "";
        // BI 抛过来的日期目前分两种，yyyyMM和yyyyMMdd，且以201508为原点开始计算
        // 校验日期格式是否符合规范, 如果某条数据statisDate不符合规范，则不选择表，丢给DB执行报错，计入报错行记录
        Matcher yyyyMMddMatcher = YYYYMMDD_PATTERN.matcher(statisDate);
        Matcher yyyyMMMatcher = YYYYMM_PATTERN.matcher(statisDate);
        if (yyyyMMddMatcher.matches() ||
                yyyyMMMatcher.matches()) {
            if (StringUtils.isNotBlank(statisDate)) {
                // 截取年份和月份
                int year = Integer.valueOf(statisDate.substring(0, 4));
                String monthStr = statisDate.substring(4, 6);
                int month = Integer.valueOf(monthStr);
                int index = (12 * (year - 2015) + month - 8) % 3;
                indexStr = String.valueOf(index);
            }
        }
        return indexStr;
    }
    
    private static void createTruncateSql(String tableName, String index, String rew) {
        System.out.println("TRUNCATE TABLE " + tableName + index + rew + ";");
    }
}
